
#ifndef __MASTER_SLAVE_H__
#define __MASTER_SLAVE_H__
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <stdatomic.h>
#include <sys/stat.h>
#include <sys/poll.h>
#include <time.h> // 用于rand种子初始化
#include "rbtree.h"
#include "hash.h"
#include "skiplist.h"
#include "nolock_list.h"
#include "public.h"

#if MASTER_SLAVE

// #define AOF_FILE_NAME "appendonly.aof"
#define META_FILE "slave_meta.dat"
#define POLL_TIMEOUT 1000
#define MASTER_ID_LEN 16 // 用16位十六进制字符串作为主机ID
#define SLAVE_ID "dcf_kvstore"
#define SLAVE_ID_MAX_LEN 16


typedef enum
{
    MODE_MASTER,
    MODE_SLAVE,
    MODE_STANDALONE
} ServerMode;

typedef struct
{
    char master_id[MASTER_ID_LEN + 1]; // 主机ID（字符串+结束符）
    off_t aof_offset;
} SlaveMeta;

typedef struct
{
    char slave_id[SLAVE_ID_MAX_LEN + 1];
    char master_id[MASTER_ID_LEN + 1];
    off_t aof_offset;
} SlaveSyncReq;

typedef struct
{
    char need_full_sync;
    off_t rb_full_size;
    off_t hash_full_size;
    off_t skiplist_full_size;

    off_t aof_size;
    off_t aof_start;

    char master_id[MASTER_ID_LEN + 1];

} MasterSyncResp;

typedef struct
{
    ServerMode mode;
    // 主机配置
    char master_id[MASTER_ID_LEN + 1]; // 主机用于验证是否需要给从机发送全量文件
    int master_listen_port;
    pthread_t master_listen_thread;
    SPSCLockFreeListQueue *slave_conns;
    RBTree *master_rbtree;
    HashTable *master_hash_table;
    SkipList *master_skiplist;
    atomic_bool master_running;

    // 从机配置
    char master_ip[32];
    int master_port;
    pthread_t slave_sync_thread;
    RBTree *slave_rbtree;
    HashTable *slave_hash_table;
    SkipList *slave_skiplist;
    atomic_bool slave_running;
    SlaveMeta slave_meta;

    // 公共配置
    char slave_id[SLAVE_ID_MAX_LEN + 1]; // 主机用于验证该从机是否可信任

} MasterSlaveConfig;



int ms_init(ServerMode mode, const char *master_ip, int master_port, int listen_port, RBTree *rbtree, HashTable *hash_table, SkipList *skiplist);
int ms_start();
void ms_stop();
#endif

#endif